//
//  TTHomeViewController.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/22.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import YYModel

class TTHomeViewController: TTBaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    var weiBoViewModel: TTWeiBoViewModel = TTWeiBoViewModel()
    
    var tableView: UITableView?
    
    //懒加载上拉加载风火轮
    private lazy var pullUpLoadView: UIActivityIndicatorView = {
        let loadView = UIActivityIndicatorView(activityIndicatorStyle:     UIActivityIndicatorViewStyle.whiteLarge)
        loadView.color = UIColor.cyan
        
        return loadView
    }()
    
    //懒加载下拉刷新
    private lazy var pullDownRefreshView: HMRefreshControl = {
        let loadView = HMRefreshControl()
        
        loadView.addTarget(self, action: #selector(pullDownToRefresh), for: .valueChanged)
        
        return loadView
    }()
    
    //懒加载加载了多少微博数据的lable
    private lazy var loadWeiBoNumLable: UILabel = {
        let lable = UILabel()
        
        lable.text = "没有加载到微博数据"
        lable.textAlignment = .center
        lable.font = UIFont.systemFont(ofSize: 16)
        lable.backgroundColor = UIColor.white
        lable.textColor = UIColor.black
        
        return lable
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(view.frame)
        
        let tableView = UITableView(frame: view.frame, style: .plain)
        self.tableView = tableView
        
        tableView.dataSource = self
        tableView.delegate = self
        
        view.addSubview(tableView)
        
        //注册
        tableView.register(TTHomeCell.self, forCellReuseIdentifier: "main")
        
        //适配行高
        tableView.estimatedRowHeight = 200
        
        //去除分割线
        tableView.separatorStyle = .none
        
        //添加footerView
        tableView.tableFooterView = pullUpLoadView
        
        //添加refreshControl子视图
        tableView.addSubview(pullDownRefreshView)
        
        //添加加载了多少条微博数据的动画lable
        setUpTheLableOfWeiBoNum()
        
        //加载网络数据
        weiBoViewModel.loadDataWithLinPai { (result) in
            if result {
                tableView.reloadData()
                //加载微博最新数据条数动画
                self.lableAnimateIfload()
            }
        }
        
        
    }
    
    
    //MARK: - 数据源
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weiBoViewModel.homeArray.count 
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "main", for: indexPath) as? TTHomeCell
        
        let weiBoViewModel = self.weiBoViewModel.homeArray[indexPath.row]
        
//        print(weiBoViewModel?.weiBoModel?.pic_urls?.count ?? 0)
        
        cell?.weiBoViewModel = weiBoViewModel
        
//        print(weiBoViewModel?.weiBoModel?.reposts_count)
        
        cell?.selectionStyle = .none
        
        return cell!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - 代理方法
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //判断如果是最后一个cell就加载
        if indexPath.row == (weiBoViewModel.homeArray.count) - 1{
            
            //用风火轮是否正在动画来判断是否正在发送请求,如果正在发送请求,就不再发送请求
            if pullUpLoadView.isAnimating == true {
                return
            }
            
            //打开风火轮动画效果
            self.pullUpLoadView.startAnimating()
        
            //发送获取更早的微博数据的请求
            weiBoViewModel.loadDataWithLinPai(isPullUp: true, backClosure: { (result) in
                if result {
                    self.tableView?.reloadData()
                    //关闭风火轮
                    self.pullUpLoadView.stopAnimating()
                }
            })
            
        }
    }
    
    //MARK: - 下拉刷新refreshControl控件监听方法
    func pullDownToRefresh(){
        
        //发送获取最新的微博数据的请求
        weiBoViewModel.loadDataWithLinPai(isPullUp: false) { (result) in
            if result {
                self.tableView?.reloadData()
                //结束下拉刷新的提示
                self.pullDownRefreshView.endRefreshing()
                //加载微博最新数据条数动画
                self.lableAnimateIfload()
            }
        }
 
    }
    
    //MARK: - 加载了多少条微博的lable的制作
    func setUpTheLableOfWeiBoNum() {
        
        //把lable放在navigationController的view上
        //视图a插入视图b的后边(离屏幕远)
        self.navigationController?.view.insertSubview(loadWeiBoNumLable, belowSubview: (self.navigationController?.navigationBar)!)
        loadWeiBoNumLable.frame = CGRect(x: 0, y: 64-35, width: ScreenWidth, height: 35)
        //隐藏
        loadWeiBoNumLable.isHidden = true
        
    }
    
    //MARK: - 如果加载了数据,lable的动画效果
    func lableAnimateIfload() {
        
        //假如lable在显示状态,也就是在动画状态,就不再执行动画
        if loadWeiBoNumLable.isHidden == false {
            return
        }
        
        loadWeiBoNumLable.isHidden = false
        //赋值加载信息
        loadWeiBoNumLable.text = weiBoViewModel.loadNumStr
        
        //向下移动lable高度
        UIView.animate(withDuration: 1, animations: {
            self.loadWeiBoNumLable.transform = CGAffineTransform(translationX: 0, y: self.loadWeiBoNumLable.frame.size.height)
        }) { (_) in
            //动画后回去
            UIView.animate(withDuration: 1, animations: {
                self.loadWeiBoNumLable.transform = CGAffineTransform.identity
            }, completion: { (_) in
                //影藏
                self.loadWeiBoNumLable.isHidden = true
            })
        }
        
    }
   
}
